package cn.hyh.core.service.impl;

import cn.hyh.core.component.GlobalStatus;
import cn.hyh.core.costant.MsgStatus;
import cn.hyh.core.dao.BlogMapper;
import cn.hyh.core.dao.ContentMapper;
import cn.hyh.core.dao.MsgMapper;
import cn.hyh.core.pojo.Blog;
import cn.hyh.core.pojo.Content;
import cn.hyh.core.pojo.Dics;
import cn.hyh.core.pojo.Msg;
import cn.hyh.core.service.ServiceInterface.DicService;
import cn.hyh.core.service.ServiceInterface.MsgService;
import cn.hyh.core.util.HttpUtils;
import cn.hyh.core.vo.MsgModel;
import cn.hyh.core.vo.PageModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @auther :hyh
 * @desc :
 * @date :2019/7/16
 */
@Service
public class MsgServiceImpl implements MsgService {
    @Resource
    private MsgMapper msgMapper;


    @Autowired
    private AsyncServiceImpl asyncService;

    @Resource
    private BlogMapper blogMapper;

    @Autowired
    private DicService dicService;

    @Transactional
    @Override
    public Msg saveMsg(MsgModel model, HttpServletRequest request) {
        Msg msg=null;
        if (model.getParent() == null && model.getArticle() == null) {
            //说明是第一次的普通的评论
            boolean emailFlag = false;
              // 说明 是第一个评论的
             msg = new Msg();
            msg.setNickName(model.getNickName())
                    .setContent(model.getContent())
                    .setCreateTime(new Date())
                    .setParent(0)
                    .setArticleId(0);
            if (checkEmail(model.getEmail())) {
                System.out.println("邮箱验证结果==>"+true);
                msg.setEmail(model.getEmail());
                emailFlag = true;
            }
            if (StringUtils.isNotEmpty(model.getAvatar())){
                msg.setAvatarImg(model.getAvatar());
            }else {

                msg.setAvatarImg(getRandomAvatar());
            }

            //获取地址
//            String address = asyncService.getAddressByIP("219.137.206.183");
            String address = asyncService.getAddressByIP(HttpUtils.getRealIp(request));
            msg.setAddress(address);
            msgMapper.insert(msg);
            if (emailFlag) {
                asyncService.sendToHost(msg, GlobalStatus.OTHER_TO_ADMIN);
            }
        }

        else  if (model.getParent() != null && model.getArticle() == null) {
              //评论的子回复
            boolean emailFlag = false;
            msg = new Msg();
            msg.setContent(model.getContent())
                    .setCreateTime(new Date())
                    .setArticleId(0)
                    .setNickName(model.getNickName())
                    .setEmail(model.getEmail());
            String address = asyncService.getAddressByIP(HttpUtils.getRealIp(request));
            msg.setAddress(address);
            if (StringUtils.isNotEmpty(model.getAvatar())){
                msg.setAvatarImg(model.getAvatar());
            }else {
                msg.setAvatarImg(getRandomAvatar());
            }
            if (checkEmail(model.getEmail())) {
                msg.setEmail(model.getEmail());
                emailFlag = true;
            }
            msg.setParent(model.getParent());
            msgMapper.insert(msg);
            if (emailFlag) {
                asyncService.sendToHost(msg,GlobalStatus.OTHER_TO_OTHER);
            }
            msg = msgMapper.selectById(model.getParent());
            msg.setChildrenMsg(getChildrenMsg(model.getParent()));
        }
        else if(model.getParent() == null && model.getArticle() != null){
              //文章的父评论。
            msg = new Msg();
            msg.setContent(model.getContent())
                    .setNickName(model.getNickName())
                    .setAddress("未知")
                    .setEmail(model.getEmail())
                    .setCreateTime(new Date())
                    .setParent(0)
                    .setArticleId(model.getArticle());
            if (StringUtils.isNotBlank(model.getAvatar())) {
                msg.setAvatarImg(model.getAvatar());
            }else {

                msg.setAvatarImg(getRandomAvatar());
            }
            Blog blog = blogMapper.selectOne(new QueryWrapper<Blog>().eq("content_id", model.getArticle()));
            blog.setComment(blog.getComment()+1);
            blogMapper.updateById(blog);
            msgMapper.insert(msg);
        }
        else if(model.getParent() != null && model.getArticle() != null){
            msg = new Msg();
            msg.setContent(model.getContent())
                    .setNickName(model.getNickName())
                    .setAddress("未知")
                    .setEmail(model.getEmail())
                    .setCreateTime(new Date())
                    .setParent(model.getParent())
                    .setArticleId(model.getArticle());
            if (StringUtils.isNotBlank(model.getAvatar())) {
                msg.setAvatarImg(model.getAvatar());
            }else {

                msg.setAvatarImg(getRandomAvatar());
            }
            Blog blog = blogMapper.selectOne(new QueryWrapper<Blog>().eq("content_id", model.getArticle()));
            blog.setComment(blog.getComment()+1);
            blogMapper.updateById(blog);
            msgMapper.insert(msg);
            msg = msgMapper.selectById(model.getParent());
            msg.setChildrenMsg(getChildrenMsg(model.getParent()));

        }

        return msg;
    }


    public  String getRandomAvatar() {
        Map<String, List<Dics>> dicMap = dicService.selectGroup();
        List<Dics> list = dicMap.get("CommentAvatar");
        int i = RandomUtils.nextInt(0, list.size());
        return list.get(i).getValue();
    }

    @Override
    public Map<String,Object> getPageList(PageModel model) {
        int num = (model.getPageNum()-1)* model.getPageSize();

        List<Msg> msgList=msgMapper.selectParentPage(num,model.getPageSize(), MsgStatus.PARENT_ID,0);
        for (Msg msg : msgList) {
            int parentId = msg.getId();
            List<Msg> msgs = getChildrenMsg(parentId);
            System.out.println(msgs.size());
            msg.setChildrenMsg(msgs);
        }

        Integer total = msgMapper.selectCount(new QueryWrapper<Msg>().eq("parent", MsgStatus.PARENT_ID).eq("article_id",MsgStatus.PARENT_ID));
        int totalPage = (int) Math.ceil(total / model.getPageSize());
        Map<String, Object> map = new HashMap<>();
        map.put("dataList", msgList);
        map.put("totalPage", totalPage);
        map.put("totalCount", total);

        return map;
    }

    @Override
    public List<Msg> articleCommentList(int id) {
        QueryWrapper<Msg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", id).eq("parent", 0).orderByDesc("create_time");
        List<Msg> msgs = msgMapper.selectList(queryWrapper);
        for (Msg msg : msgs) {
            QueryWrapper<Msg> query = new QueryWrapper<>();
            query.eq("article_id", id).eq("parent", msg.getId()).orderByDesc("create_time");;
            List<Msg> msgList = msgMapper.selectList(query);
            if (msgList != null && msgList.size() > 0) {
                msg.setChildrenMsg(msgList);
            }
        }
        return msgs;
    }


    public  List<Msg>  getChildrenMsg(int parentId){
        List<Msg> msgs = msgMapper.selectList(new QueryWrapper<Msg>().eq("parent", parentId).orderByDesc("create_time"));
        if (msgs != null && msgs.size() > 0) {
            return msgs;
        }
        return new ArrayList<>();
    }


    /**
     * 检查邮箱 是否复合规则，不符合 ，就不存储。
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {

        String regex = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";

        if (email.matches(regex)) {
            return  true;
        }
        return false;

    }

}
